﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Diagnostics;

namespace WildstarRelogger
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.login.Text = Properties.Settings.Default.login;
            this.password.Text = Properties.Settings.Default.password;
            this.browselauncherexe.Text = Properties.Settings.Default.path;
            this.launchertime.SelectedIndex = Properties.Settings.Default.launchertimeindex;
            this.loginwindowtime.SelectedIndex = Properties.Settings.Default.loginwindowindex;
            this.charactertime.SelectedIndex = Properties.Settings.Default.characterindex;
            this.loginpassworddelay.SelectedIndex = Properties.Settings.Default.loginpasswordindex;
            string[] arguments = Environment.GetCommandLineArgs();
            if (arguments.Length > 1)
            {
                if (arguments[1] == "-start")
                {
                    start_wildstar();
                    Thread start = new Thread(monitor_ws);
                    start.IsBackground = true;
                    start.Start();
                }
            }
        }

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(String sClassName, String sAppName);
        [DllImport("User32.dll")] 
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
        //[DllImport("user32.dll")]
        //public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);
        [DllImport("user32.dll")]
        static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);
        private bool ShouldIStop = false;

        [BindableAttribute(true)]
        public double Position { get; set; }

        private void launch_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();
            start_wildstar();
            Thread start = new Thread(monitor_ws);
            start.IsBackground = true;
            start.Start();
        }

        private void click_launcher()
        {
            Process[] pname = Process.GetProcessesByName("WildStar64");
            if (pname.Length == 0)
            {
                IntPtr handle = FindWindow("#32770", "WildStar 100%");
                if (!handle.Equals(IntPtr.Zero))
                {
                    RECT rect = new RECT();
                    if (GetWindowRect(handle, ref rect))
                    {
                        
                        
                        if (SetForegroundWindow(handle))
                        {
                            //var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                            //var width = screen.Width;
                            //var height = screen.Height;

                            //Size cSize = GetControlSize(handle);
                            ////float percentwi = (700f * 100f) / (float)width;
                            ////float percenthei = (555f * 100f) / (float)height;
                            ////float clientX = (float)width / 100f;
                            ////float clientY = (float)height / 100f;
                            ////float clientpX = percentwi * clientX;
                            ////float clientpY = percenthei * clientY;

                            ////int X = (int)Math.Round(clientpX);
                            ////int Y = (int)Math.Round(clientpY);
                            //int X = cSize.Width - 200;
                            //int Y = cSize.Height - 200;

                            //Point clientpoint = new Point(X, Y);
                            //ClientToScreen(handle, ref clientpoint);
                            //Cursor.Position = new Point(X, Y);

                            ////mouse_event(0x00000002, 0, 0, 0, UIntPtr.Zero); /// left mouse button down
                            ////mouse_event(0x00000004, 0, 0, 0, UIntPtr.Zero); /// left mouse button up

                            for (int i = 0; i <= 12; i++)
                            {
                                SendKeys.SendWait("{TAB}");
                            }
                            SendKeys.SendWait(" ");
                        }
                    }
                }
                int sleeptime = thread_helper(loginwindowtime);
                Thread.Sleep(sleeptime);
                login_ws();
            }
        }

        public static Size GetControlSize(IntPtr hWnd)
        {
            RECT rect = new RECT();
            Size cSize = new Size();
            // get coordinates relative to window
            GetWindowRect(hWnd, ref rect);

            cSize.Width = rect.Right - rect.Left;
            cSize.Height = rect.Bottom - rect.Top;
            

            return cSize;
        }



        private void enter_realm()
        {

        }

        private void login_ws()
        {
            Process[] pname = Process.GetProcessesByName("WildStar64");
            if (pname.Length == 1)
            {
                IntPtr handle = FindWindow("WildStar 6731", "WildStar 6731");
                //Process[] p = Process.GetProcessesByName("wildstar");

                if (!handle.Equals(IntPtr.Zero))
                {

                    // Activate WS window
                    if (SetForegroundWindow(handle))
                    {
                        int loginpassword = thread_helper(loginpassworddelay);
                        
                        // send login informations
                        SendKeys.SendWait(login.Text);
                        Thread.Sleep(loginpassword);
                        SendKeys.SendWait("{TAB}");
                        Thread.Sleep(100);
                        SendKeys.SendWait(password.Text);
                        Thread.Sleep(loginpassword);
                        SendKeys.SendWait("{ENTER}");
                        int sleeptime = thread_helper(charactertime);
                        Thread.Sleep(sleeptime);
                        SendKeys.SendWait("{ENTER}");
                    }
                }
            }
        }

        private void btn_launcherexe_Click(object sender, EventArgs e)
        {
            OpenFileDialog launcherexe = new OpenFileDialog();

            if (launcherexe.ShowDialog() == DialogResult.OK)
                browselauncherexe.Text = launcherexe.FileName.ToString();

        }

        public void start_ws()
        {
            Process[] wildstar = Process.GetProcessesByName("Wildstar");
            Process[] pname = Process.GetProcessesByName("WildStar64");
            if (pname.Length == 0 && wildstar.Length == 0)
            {
                try
                {
                    ProcessStartInfo pInfo = new ProcessStartInfo();
                    pInfo.FileName = browselauncherexe.Text;
                    Process p = Process.Start(pInfo);
                    int sleeptime = thread_helper(launchertime);
                    Thread.Sleep(sleeptime);
                    click_launcher();
                }
                catch (Exception e) 
                 {
                     MessageBox.Show(e.ToString());
                  }
            }
        }

        private void start_wildstar()
        {
            Thread start = new Thread(start_ws);
            start.IsBackground = true;
            start.Start();
        }
       
        private void monitor_ws()
        {
            Thread.Sleep(25000);
            
            while (!ShouldIStop)
            {
                Process[] pname = Process.GetProcessesByName("WildStar64");
                Process[] wildstar = Process.GetProcessesByName("Wildstar");
                if (pname.Length == 0 && wildstar.Length == 0)
                {
                    Thread start = new Thread(start_ws);
                    start.IsBackground = true;
                    start.Start();
                }
                Thread.Sleep(1000);
            }
            
                
        }

        private void stopmonitor_Click(object sender, EventArgs e)
        {
            stop();
        }

        public void stop()
        {
            ShouldIStop = true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ShouldIStop = true;
            Properties.Settings.Default.login = this.login.Text.ToString();
            Properties.Settings.Default.password = this.password.Text.ToString();
            Properties.Settings.Default.path = this.browselauncherexe.Text.ToString();
            Properties.Settings.Default.launchertimeindex = this.launchertime.SelectedIndex;
            Properties.Settings.Default.loginwindowindex = this.loginwindowtime.SelectedIndex;
            Properties.Settings.Default.characterindex = this.charactertime.SelectedIndex;
            Properties.Settings.Default.loginpasswordindex = this.loginpassworddelay.SelectedIndex;
            Properties.Settings.Default.Save();
        }


        public int thread_helper(ComboBox componentname)
        {
            int time = 10000;
            this.Invoke((MethodInvoker)delegate()
            {
                if (componentname.SelectedItem != null)
                {
                    time = int.Parse(componentname.SelectedItem.ToString()) * 1000;
                }
            });
            return time;            
        }
    }
}
